package net.easyjava.tools.http.ftp;

import java.io.*;
import java.net.SocketException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;

import net.easyjava.tools.lang.StringTools;
import org.apache.commons.io.IOUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * class name:FtpTools <BR>
 * class description: please write your description <BR>
 * Remark: <BR>
 *
 * @version 1.00 2011-8-9
 */
public class FtpTools {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private String ftpPath;
    private String ftpName;
    private String ftpPassword;
    private String ftpServerIP;

    public FtpTools(String ftpName,String ftpPassword,String ftpServerIP) {
        this.ftpPath = "";
        this.ftpName = ftpName;
        this.ftpPassword = ftpPassword;
        this.ftpServerIP = ftpServerIP;
    }

    /**
     * Method name: saveFile <BR>
     * Description: 把文件存储在FTP上 <BR>
     * Remark: <BR>
     *
     * @param folderName 示例"xxx/xxx/"
     * @param fileName   示例"thefileName"
     * @param sourcePath       数据源文件地址
     * @return boolean<BR>
     */
    public boolean saveFile(String folderName, String fileName, String sourcePath){
        Path path = Paths.get(sourcePath);
        try(InputStream is = Files.newInputStream(path);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();) {
            byte[] bytes = new byte[1024];
            while((is.read(bytes))>0){
                baos.write(bytes);
            }
            return saveFile(folderName, fileName, baos.toByteArray());
        }catch (IOException e){
            logger.error(e.getMessage(),e.fillInStackTrace());
            return false;
        }
    }

    /**
     * Method name: saveFile <BR>
     * Description: 把文件存储在FTP上 <BR>
     * Remark: <BR>
     *
     * @param folderName 示例"xxx/xxx/"
     * @param fileName   示例"thefileName"
     * @param data       byte[]数组
     * @return boolean<BR>
     */
    public boolean saveFile(String folderName, String fileName, byte[] data) {
        boolean flag = false;
        
        if(folderName.startsWith("/")){
            throw new IllegalArgumentException("folderName is error");
        }
        if(fileName == null || "".equals(fileName) || folderName == null || "".equals(folderName)){
            throw new NullPointerException("fileName or folderName can't be null");
        }
        // 创建FTP客户端
        FTPClient ftpClient = new FTPClient();
        // 输入流用于读取文件
//		FileInputStream fis = null;
        ByteArrayInputStream bis = null;

        try {
            // 如果folderName 和 fileName都不符合基本要求, 那么就没有必要进行ftp操作

                // 建立FTP连接
                ftpClient.connect(this.ftpServerIP);

                // 如果登录成功后, 才进行创建输入流
                if (ftpClient.login(this.ftpName, this.ftpPassword)) {
//					File srcClientFile = new File("C:/ParseXML.xml");

                    // 实例化输入流
//					fis = new FileInputStream(srcClientFile);

                    String[] paths= folderName.split("/");
                    StringBuffer sb = new StringBuffer();
                    for(String path:paths){
                        String dir = path+"/";
                        if(!ftpClient.changeWorkingDirectory(dir)){
                            ftpClient.makeDirectory(dir);
                            ftpClient.changeWorkingDirectory(dir);
                        }
                    }

                    // 将byte[]写入到输入流中, 实例化
                    bis = new ByteArrayInputStream(data);

                    // 设置缓冲
                    ftpClient.setBufferSize(1024);

                    // 设置文件类型(二进制类型)
                    if (ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE)) {
                        flag = ftpClient.storeFile(fileName, bis);
                    }
                }
        } catch (SocketException e) {
            e.printStackTrace();
            logger.error(e.getMessage(),e.fillInStackTrace());
            flag = false;
        } catch (IOException e) {
            e.printStackTrace();
            logger.error(e.getMessage(),e.fillInStackTrace());
            flag = false;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage(), e.fillInStackTrace());
            flag = false;
        } finally {
            try {
                // 关闭输入流
                IOUtils.closeQuietly(bis);
                // 关闭连接
                ftpClient.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return flag;
    }

    /**
     * Method name: getFromFTP <BR>
     * Description: 从FTP上读取文件 <BR>
     * Remark: <BR>
     *
     * @return boolean<BR>
     */
    public boolean getFromFTP() {
        boolean flag = false;

        // 创建FTP客户端
        FTPClient ftpClient = new FTPClient();
        // 输出流用于输出文件
        FileOutputStream fos = null;

        try {
            // 建立FTP连接
            ftpClient.connect(this.ftpServerIP);
            // 如果登录成功后, 才进行创建输出流
            if (ftpClient.login(this.ftpName, this.ftpPassword)) {
                // FTP文件
                String distinationFile = "/name/xxx/xxx/xxx文件";
                // 实例化输出流
                fos = new FileOutputStream("C:/ParseXML_InFTP.xml");

                // 设置缓冲
                ftpClient.setBufferSize(1024);

                // 设置文件类型(二进制类型)
                if (ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE)) {
                    ftpClient.retrieveFile(distinationFile, fos);
                    flag = true;
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
            flag = false;
        } catch (IOException e) {
            e.printStackTrace();
            flag = false;
        } catch (Exception e) {
            e.printStackTrace();
            flag = false;
        } finally {
            try {
                // 关闭输出流
                IOUtils.closeQuietly(fos);
                // 关闭连接
                ftpClient.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return flag;
    }

    public boolean createDirectory() {
        boolean flag = false;

        // 创建FTP客户端
        FTPClient ftpClient = new FTPClient();

        try {
            // 建立FTP连接
            ftpClient.connect(this.ftpServerIP);
            // 如果登录成功后, 才进行操作
            if (ftpClient.login(this.ftpName, this.ftpPassword)) {

                // 切换文件路径, 到FTP上的"NNDD3"文件夹下
                if (this.ftpPath != null && this.ftpPath.compareTo("") != 0
                        && ftpClient.changeWorkingDirectory(this.ftpPath)) {
                    SimpleDateFormat f = new SimpleDateFormat("yyyyMMdd");
                    String time = f.format(new Date());

                    String folderName = time + "_ReTransmit";
                    ftpClient.makeDirectory(folderName);
                    flag = true;
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
            flag = false;
        } catch (IOException e) {
            e.printStackTrace();
            flag = false;
        } catch (Exception e) {
            e.printStackTrace();
            flag = false;
        } finally {
            try {
                // 关闭连接
                ftpClient.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return flag;
    }

    public String[] getAllfolderNames() {
        // 创建FTP客户端
        FTPClient ftpClient = new FTPClient();

        try {
            // 建立FTP连接
            ftpClient.connect(this.ftpServerIP);

            // 如果登录成功后, 才进行操作
            if (ftpClient.login(this.ftpName, this.ftpPassword)) {

                // 切换文件路径, 到FTP上的"NNDD3"文件夹下
                if (this.ftpPath != null && this.ftpPath.compareTo("") != 0
                        && ftpClient.changeWorkingDirectory(this.ftpPath)) {
                    // 将当前时间减去2天, 删除的是前两天的数据包
                    String time = minusTime();

                    String[] allNames = ftpClient.listNames();

                    String[] temp = new String[allNames.length];
                    // 初始化数组
                    for (int j = 0; j < allNames.length; j++) {
                        temp[j] = "";
                    }

                    // 找出要删除文件夹的名称
                    for (int i = 0; i < allNames.length; i++) {
                        if (allNames[i].substring(0, 8).compareTo(time) <= 0) {
                            temp[i] = allNames[i];
                        }
                    }

                    return temp;
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 关闭连接
                ftpClient.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return null;
    }

    /**
     * Method name: minusTime <BR>
     * Description: 获取钱两天的时间,如2011-8-1的前两天就是2011-7-30 <BR>
     * Remark: <BR>
     *
     * @return String<BR>
     */
    private String minusTime() {
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
        Date d = new Date();
        String timeMinus2 = df.format(new Date(d.getTime() - 2 * 24 * 60 * 60 * 1000));
        return timeMinus2;
    }

    public static void main(String[] args) {
        FtpTools ftpTools = new FtpTools("wenxiaoning","wenxiaoning","101.200.193.65");
        try {
            InputStream is = new FileInputStream(new File("/data/user-center/quest/win-20151225.properties"));
            byte[] bytes = new byte[1024];
            String content = "好";
            is.read(bytes);
            ftpTools.saveFile("file/article/" + StringTools.getRandomDir(4),
                    System.currentTimeMillis()+".txt",
                    "/data/user-center/quest/win-20151225.properties");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
//        ftpTools.deleteFoldersInFTP();

//		boolean flag = FtpTools.createDirectory();
//		if (flag) {
//			System.out.println("****** FTP文件夹创建成功 ******");
//		}

//		String folderName = FtpTools.ftpPath + "20110809_ReTransmit/";
//		byte[] data = new byte[1024];
//		for (int i = 0; i < data.length; i ++) {
//			data[i] = 'a';
//		}
//		boolean flag = FtpTools.saveInFTP(folderName, "2011080912345678" ,data);
//		if (flag) {
//			System.out.println("****** FTP文件夹创建成功 ******");
//		}
    }
}